#!/usr/bin/perl
use CGI;
use strict;
use warnings;
use C4::Context;
use XML::Simple;
use LWP::Simple;

use LWP::UserAgent;
use HTTP::Request::Common;

my $cgi = new CGI;
binmode(STDOUT, "utf8"); #output as utf8
my $baseurl = C4::Context->preference('OPACBaseURL');
my $libname = C4::Context->preference('LibraryName');
my $opacimage = C4::Context->preference('opacsmallimage');
my $indexname = C4::Context->preference('indexname');

my $q = $cgi->param('q');
my $index = $cgi->param('searchindex');
my $startpage = $cgi->param('startPage') | 1;
my $count = $cgi->param('count') | 20;

if ($q) {
    # koha:isbn:0152018484
	my $url = "http://$baseurl:9998/biblios?version=1.1&operation=searchRetrieve&query=$q&startRecord=$startpage&maximumRecords=$count&recordSchema=rss2";
    my $content = get($url);
    print $cgi->header( -type =>'text/xml' );
    print $content;
}

else {

print $cgi->header( -type =>'text/xml' );
print "<?xml version='1.0' encoding='utf-8'  ?>";
print "<OpenSearchDescription \n\txmlns=\"http://a9.com/-/spec/opensearchdescription/1.0/\"\n\txmlns:openIll=\"http://open-ils.org/xml/openIll/1.0\">";
print "\n<Url>http://$baseurl/cgi-bin/koha/opensearch?q={searchTerms}&amp;searchindex=$indexname&amp;startPage={startPage}&amp;count={count}</Url>";
print "\n<Url type=\"application/rss+xml\" template=\"http://$baseurl/cgi-bin/koha/opensearch?q={searchTerms}&amp;searchindex=$indexname&amp;startPage={startPage}&amp;count={count}\"/>";
print "\n<Url type=\"text/html\" template=\"http://$baseurl/cgi-bin/koha/opensearch?q={searchTerms}\"/>";
print "\n<Format>http://a9.com/-/spec/opensearchrss/1.0/</Format>";
print "\n<ShortName>Koha</ShortName>";
print "\n<LongName>$libname</LongName>";
print "\n<Description>Search for items the in $libname catalog</Description>";
print "\n<Tags>Koha ILS at $libname</Tags>";
print "\n<Image>$opacimage</Image>";
print "\n<SampleSearch>cryptonomicon</SampleSearch>";
print "\n<Developer>Joshua Ferraro</Developer>";
print "\n<Contact>jmf\@liblime.com</Contact>";
print "\n<Attribution>Koha from LibLime: http://liblime.com/koha</Attribution>";
print "\n<SyndicationRight>open</SyndicationRight>";
print "\n<AdultContent>false</AdultContent>";
print "\n</OpenSearchDescription>";

}
